#!/usr/bin/php
<?php

function main($argc, & $argv)
{
    $sd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
    if (!$sd) {
        echo socket_strerror(socket_last_error($sd)), PHP_EOL;
        return 0;
    }

    if (!socket_bind($sd, "3.3.3.9", 9999)) {
        echo socket_strerror(socket_last_error($sd)), PHP_EOL;
        goto ERR1;
    }

    if (!socket_listen($sd, 5)) {
        echo socket_strerror(socket_last_error($sd)), PHP_EOL;
        goto ERR1;
    }


    for ($i = 0; $i < 5; ++$i) {
        if (pcntl_fork() == 0) {
            while (1) {
            $cli = socket_accept($sd);
            $packet = socket_read($cli, 8192);
            socket_getpeername($cli, $ip, $port);
            echo $ip, "[", $port, "]: ", $packet, PHP_EOL;

            $http = "HTTP/1.1 200 OK\r\n";
            $http .= "Host:3.3.3.9\r\n";
            $http .= "Connection:close\r\n";
            $http .= "Content-Type:text/html;charset=UTF-8\r\n";
            $http .= "Content-Length:16\r\n";
            $http .= "\r\nkyo http server!";

            socket_write($cli, $http, strlen($http));
            socket_close($cli);
            }
        }
    }

    fgets(STDIN);

    posix_kill(0, SIGTERM);

ERR1:
    socket_close($sd);

    return 0;
}

exit(main($argc, $argv));

